package org.platform.tool.util;


import com.mc.mic.core.tool.helper.SpringContextHelper;
import org.platform.dao.mapper.FdSerialNumberMapper;
import org.platform.mo.db.FdSerialNumber;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 流水号工具类
 *
 * @author FengJie
 * @date 2018/7/18
 */
public class SerialNumberUtils {
    private static final String KEY_FORMAT = "yyyy-MM-dd";
    public static final int MAX = 999;
    public static int MIN = 1;
    private static SerialNumberUtils serialNumberUtils;

    private SerialNumberUtils() {
    }

    public static SerialNumberUtils getInstance() {
        synchronized (SerialNumberUtils.class) {
            if (serialNumberUtils == null) {
                serialNumberUtils = new SerialNumberUtils();
                return serialNumberUtils;
            } else {
                return serialNumberUtils;
            }
        }
    }

    /**
     * 获取当前最大的流水号
     *
     * @return 最大流水号
     */
    public String getSerialNumber() {
        Integer serialNumber;
        FdSerialNumberMapper mapper = SpringContextHelper.getBean(FdSerialNumberMapper.class);
        String today = new SimpleDateFormat(KEY_FORMAT).format(new Date());
        FdSerialNumber fdSerialNumber = mapper.selectByPrimaryKey(today);
        //如果当天已经存在流水号,判断流水号,并且修改系统流水号
        if (fdSerialNumber != null) {
            Integer thisSerialNumber = fdSerialNumber.getSerialNumber();
            if (thisSerialNumber > MAX) {
                serialNumber = MIN;
            } else {
                serialNumber = ++thisSerialNumber;
            }
            fdSerialNumber.setSerialNumber(serialNumber);
            mapper.updateByPrimaryKey(fdSerialNumber);

            //如果当天未产出流水号,初始化为最小值
        } else {
            serialNumber = MIN;
            FdSerialNumber fdSerialNumber1 = new FdSerialNumber();
            fdSerialNumber1.setToday(today);
            fdSerialNumber1.setSerialNumber(MIN);
            mapper.insert(fdSerialNumber1);
        }
        return String.format("%03d", serialNumber);
    }

}
